package com.finalhomework.dms.controller;

import com.finalhomework.dms.dao.DorRepository;
import com.finalhomework.dms.dao.StudentRepository;
import com.finalhomework.dms.entities.Dormitory;
import com.finalhomework.dms.entities.Students;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class DorController {

    @Autowired
    DorRepository dorRepository;
    @Autowired
    StudentRepository studentRepository;
    @RequestMapping("/dormitory")
    public String dorList(Model model){

        List<Dormitory> aDormitory=dorRepository.findAll();
        model.addAttribute("aDormitory",aDormitory);
        return "Dormitory/dorList";
    }

    @GetMapping("/DorAdd")
    public String toAddDormitory(Model model){

        Dormitory aDormitory=new Dormitory();
        List<Students> students=studentRepository.findAll();
        model.addAttribute("dormitory",aDormitory);
        model.addAttribute("allStudents",students);
        return "Dormitory/addDor";
    }

    @PostMapping("/dormitory/save")
    public String createDormitory(Model model, Dormitory dormitory){
        dorRepository.save(dormitory);
        /*Iterable<Students> allById = studentRepository.findAllById(students);
        for (Students student : allById){
            student.setDormitory(dormitory);
            studentRepository.save(student);
        }*/
        return "redirect:/dormitory";
    }

    @GetMapping("/deldor/{id}")
    public String deleteDormitory(@PathVariable("id")int id,Model model){
        Dormitory dormitory=dorRepository.getDormitoryById(id);
        if (dormitory.getHabitableNum()==0) {
            dorRepository.deleteById(id);
            return "redirect:/dormitory";
        }else {
            model.addAttribute("msg","该宿舍仍有学生居住，请先转移学生");
            List<Dormitory> aDormitory=dorRepository.findAll();
            model.addAttribute("aDormitory",aDormitory);
            return "Dormitory/dorList" ;
        }
    }
}
